<template>
  <div class="btn-container">
    <el-tooltip effect="dark" content="标点" placement="left">
      <el-button icon="el-icon-location-outline" @click="drawPoint"></el-button>
    </el-tooltip>
    <br />

    <el-tooltip effect="dark" content="测距" placement="left">
      <el-button icon="el-icon-sort-up" @click="measureLine"></el-button>
    </el-tooltip>
    <el-tooltip effect="dark" content="测面" placement="left">
      <el-button icon="el-icon-house" @click="measurePolygon"></el-button>
    </el-tooltip>
    <br />

    <el-tooltip effect="dark" content="删除" placement="left">
      <el-button icon="el-icon-delete" @click="delDraw"></el-button>
    </el-tooltip>
  </div>
</template>

<script>
import { drawType } from "../config/draw";
import { showTip } from "../config/feature";

export default {
  props: ["map"],

  data() {
    return {
      baseMap: null,
      view: null,
      draw: null,
      tip: [],
    };
  },

  methods: {
    drawPoint() {
      // 标点
      this.startDraw("Point");
      this.endDraw("Point");
    },
    measureLine() {
      // 测距
      this.startDraw("LineString");
      this.endDraw("LineString");
    },
    measurePolygon() {
      // 测面
      this.startDraw("Polygon");
      this.endDraw("Polygon");
    },
    delDraw() {
      // 删除
      let source = this.getVectorSource();
      source.clear();
      this.tip.forEach((v) => {
        this.baseMap.removeOverlay(v);
      });
    },
    getVectorSource() {
      let layersGroup = this.baseMap.getAllLayers();
      let vector = layersGroup[4];
      return vector.getSource();
    },
    startDraw(type) {
      let source = this.getVectorSource();
      this.draw = drawType(source, type);
      this.baseMap.addInteraction(this.draw);
      this.$store.commit("updateDraw", true);
    },
    endDraw(type) {
      this.draw.on("drawend", (evt) => {
        let tip = showTip(evt, type);
        this.baseMap.addOverlay(tip);
        this.tip.push(tip);
        this.baseMap.removeInteraction(this.draw);
        this.$store.commit("updateDraw", false);
      });
    },
  },

  watch: {
    map() {
      this.baseMap = this.map;
      this.view = this.baseMap.getView();
    },
  },
};
</script>

<style scoped>
.btn-container {
  display: flex;
  flex-direction: column;
}
.el-button + .el-button {
  margin: 0;
}
.el-button,
.el-button.is-round {
  padding: 10px;
}
</style>